import { monitorServerControllerStationDetail } from '@/services/ess/alertConfig';
import { sysProfileControllerProfile as queryCurrentUser } from '@/services/ess/sysProfile';
import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { PageContainer } from '@ant-design/pro-components';
import { PageLoading } from '@ant-design/pro-layout';
import type { RequestConfig, RunTimeLayoutConfig } from '@umijs/max';
import { getLocale, history, Link, setLocale, useIntl } from '@umijs/max';
import { Button, ConfigProvider, Result } from 'antd';
import { useEffect, useState } from 'react';
import defaultSettings from '../config/defaultSettings';
import { PROXY_SERVER_URL } from '../config/proxy';
import { CustomizeRenderEmpty } from './components/Empty/';
import Header from './components/Header';
import { errorConfig } from './requestErrorConfig';

const loginPath = '/user/login';
const isDev = process.env.NODE_ENV === 'development';
let homePath = '';

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request: RequestConfig = {
  ...errorConfig,
};

// 获取菜单上的权限标志
function filterAccess(targetArr: API.SysMenu[]) {
  const resultArr: string[] = [];

  function handle(tempArr: API.SysMenu[]) {
    tempArr?.map((item: API.SysMenu) => {
      if (item.perms) resultArr.push(item.perms);
      if (Array.isArray(item.routes)) {
        handle(item.routes);
      }
    });
  }

  handle(targetArr);
  return resultArr;
}

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<
  API.UserProfileVo & {
    settings?: Partial<LayoutSettings>;
    currentUser?: API.CurrentUser;
    loading?: boolean;
    stationName?: string;
    stationId?: number | string | undefined;
    oldStation?: boolean;
    uiVersion?: number;
    isPhotovoltaic: boolean;
    fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
    updateStationInfo?: () => Promise<API.CurrentUser | undefined>;
  }
> {
  const getImageBase64 = async () => {
    return new Promise(async (resolve, reject) => {
      const image = await import('@/assets/img/default.png'); // 导入图片
      const response = await fetch(image.default); // 获取图片的响应
      const blob = await response.blob();
      const reader = new FileReader();

      reader.onload = () => {
        const base64 = reader.result; // 获取base64编码
        resolve(base64); // 将base64编码作为Promise的结果返回
      };

      reader.readAsDataURL(blob); // 将图片转换为base64
    });
  };

  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser();
      const userInfo = msg.data || {};

      // 从本地存储中读取站点信息
      const savedStationId = sessionStorage.getItem('stationId');
      let selectedStation;

      if (savedStationId) {
        // 查找保存的站点信息
        userInfo.tenants?.forEach((tenant) => {
          tenant.stationInfos?.forEach((station) => {
            if (station.id.toString() === savedStationId) {
              selectedStation = station;
            }
          });
        });
      }

      if (!selectedStation) {
        // 如果没有保存的站点信息，默认选中第一个站点
        const selectedTenant = userInfo?.tenants?.[0];
        selectedStation = selectedTenant?.stationInfos?.[0];
      }
      const tenantId = selectedStation?.tenantId?.toString();
      const stationId = selectedStation?.id?.toString();
      const stationName = selectedStation?.stationName;
      const oldStation = selectedStation?.oldStation;
      const stationCode = selectedStation?.stationCode;
      const uiVersion = selectedStation?.uiVersion;
      const isPhotovoltaic =
        selectedStation?.stationType === '6' || selectedStation?.stationType === '2';
      const isArea = selectedStation?.isArea;

      sessionStorage.setItem('stationId', stationId || '');

      homePath =
        (userInfo.routes ?? []).filter((route) => route.platformType !== 'APP')?.[0]?.path ?? // 过滤掉 APP 路由
        '/overView'; // 如果没有找到合适的路由，默认使用 /overView

      const avatar = await getImageBase64(); // 获取默认图片

      return {
        ...userInfo,
        loading: false,
        avatar: userInfo?.avatar || avatar,
        tenantId,
        stationId,
        stationName,
        oldStation,
        uiVersion,
        isPhotovoltaic,
        stationCode,
        isArea,
        routes: userInfo.routes,
        perms: [...(userInfo.perms || []), ...filterAccess(userInfo.routes)],
      };
    } catch (error) {
      console.error(error);
      // history.push(loginPath);
    }
    return undefined;
  };

  // 更新站点信息
  const updateStationInfo = (latestState) => {
    return queryCurrentUser().then((res) => {
      if (res?.success) {
        const tenants = res.data?.tenants;
        const stationInfo = tenants
          ?.find((tenant) => tenant.tenantId == latestState?.tenantId)
          ?.stationInfos?.find((station) => station.id == latestState?.stationId);

        // 更新的是当前选中的站点
        if (stationInfo) {
          return {
            tenants,
            stationName: stationInfo?.stationName,
          };
        } else {
          // 当前选中站点被删除，切换到第一站点
          const selectedStation = tenants?.[0]?.stationInfos?.[0];
          const tenantId = selectedStation?.tenantId?.toString();
          const stationId = selectedStation?.id?.toString();
          const stationName = selectedStation?.stationName;
          const oldStation = selectedStation?.oldStation;
          const isArea = selectedStation?.isArea;
          const isPhotovoltaic =
            selectedStation?.stationType === '6' || selectedStation?.stationType === '2';
          const stationCode = selectedStation?.stationCode;
          const uiVersion = selectedStation?.uiVersion;
          sessionStorage.setItem('stationId', stationId || '');
          return {
            tenants,
            tenantId,
            stationId,
            stationName,
            oldStation,
            isPhotovoltaic,
            uiVersion,
            isArea,
            stationCode,
          };
        }
      } else {
        return {};
      }
    });
  };

  // 从 localStorage 获取存储的语言设置
  const savedLocale = localStorage.getItem('locale');
  if (savedLocale) {
    setLocale(savedLocale, false); // 设置语言，不刷新页面
  } else {
    console.log('No saved locale found, using default:', getLocale());
  }

  const commonState = {
    fetchUserInfo,
    updateStationInfo,
    settings: defaultSettings as Partial<LayoutSettings>,
    isDev,
    proxyServerUrl: isDev ? PROXY_SERVER_URL : '',
    loading: true,
  };

  // 如果不是登录页面，执行
  const { location } = history;
  if (location.pathname === '/h5/appDownload') {
    return {};
  } else {
    if (location.pathname !== loginPath) {
      let currentUser = await fetchUserInfo();
      return {
        ...commonState,
        ...currentUser,
      };
    }
    return {
      ...commonState,
    };
  }
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  const [collapsed, setCollapsed] = useState(false);
  const intl = useIntl();
  const [dynamicStationName, setDynamicStationName] = useState('');
  useEffect(() => {
    const fetchStationName = async () => {
      const currentPath = location.pathname;
      if (currentPath.startsWith('/remoteUpgrade/remoteMaintenance')) {
        const searchParams = new URLSearchParams(location.search);
        const stationIdStr = searchParams.get('stationid');

        if (stationIdStr) {
          const stationId = parseInt(stationIdStr, 10);
          if (!isNaN(stationId)) {
            try {
              const response = await monitorServerControllerStationDetail({ stationId });
              if (response.success && response.data) {
                setDynamicStationName(response.data.stationName || '');
              }
            } catch (error) {
              console.error('Failed to fetch station details:', error);
            }
          }
        }
      }
    };

    fetchStationName();
  }, [location.pathname, location.search]);
  return {
    ...initialState?.settings,
    siderWidth: 220,
    collapsed,
    fixedHeader: true,
    fixSiderbar: true,
    collapsedButtonRender: false,
    onCollapse: setCollapsed,
    menuDataRender: (menuData) => {
      const routes = initialState?.routes ? [...initialState?.routes] : [];
      return routes;
    },
    links: [
      <a onClick={() => setCollapsed(!collapsed)} key="collapsed">
        {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
      </a>,
    ],
    footerRender: false,
    onPageChange: (routeObj) => {
      const { location } = history;
      //如果没有登录，重定向到 login
      // if (!initialState?.userId && location.pathname !== loginPath) {
      //   history.push(loginPath);
      // }

      if (routeObj?.pathname === '/') {
        history.push(homePath);
      }

      // 把目录地址类型重定向到第一个子路由
      const directoryRoute = [...(initialState?.routes || [])].find(
        (item) => item.routes?.length && item.path && item.path === routeObj?.pathname,
      );
      const redirectPath = directoryRoute?.routes?.[0]?.path;
      if (redirectPath) {
        console.log(redirectPath);
        history.push(redirectPath);
      }
    },
    // 自定义 403 页面
    unAccessible: (
      <Result
        status="403"
        title="403"
        subTitle={intl.formatMessage({ id: 'login.noPermission' })}
        extra={
          <Link to={`/`} key="goHome">
            <Button type="primary">{intl.formatMessage({ id: 'login.back' })}</Button>
          </Link>
        }
      />
    ),
    // 增加一个 loading 的状态
    childrenRender: (children) => {
      if (initialState?.loading) return <PageLoading />;
      return (
        <PageContainer title={false}>
          <ConfigProvider renderEmpty={CustomizeRenderEmpty}>{children}</ConfigProvider>
        </PageContainer>
      );
    },
    menuHeaderRender: false,
    headerRender: (props) => <Header title={props.title} />,
    title: intl.formatMessage({ id: 'login.poster' }),
    breadcrumbRender: (routers = []) => {
      const currentPath = window.location.pathname;
      let breadcrumbs = [
        {
          path: '/',
          breadcrumbName: intl.formatMessage({ id: 'global.current' }),
        },
        ...routers,
      ];

      // 如果当前路径是 /overView，则不显示面包屑导航
      if (currentPath === '/overView') {
        return [];
      }

      // 获取 URL 参数中的 stationid
      const searchParams = new URLSearchParams(window.location.search);
      const stationId = searchParams.get('stationid');

      // 处理远程维护详情页面的面包屑
      if (currentPath.startsWith('/remoteUpgrade/remoteMaintenance/detail') && dynamicStationName) {
        breadcrumbs = [
          {
            path: '/',
            breadcrumbName: intl.formatMessage({ id: 'global.current' }),
          },
          {
            path: '/remoteUpgrade',
            breadcrumbName: '远程升级',
          },
          {
            path: '/remoteUpgrade/remoteMaintenance',
            breadcrumbName: '站点服务器管理',
          },
          {
            path: currentPath + location.search,
            breadcrumbName: dynamicStationName,
          },
        ];
      }
      return breadcrumbs;
    },
  };
};
